﻿using System.IO;
using Microsoft.Practices.Unity;
using TrackIT.Common.Providers;
using System;

namespace TrackIT.Common.Repositories
{
    public delegate void WorkfileChangedHandler();

    public sealed class FileChangeNotifyProvider : IFileChangeNotifyProvider, IDisposable
    {
        private readonly FileSystemWatcher _fileWatcher;
        private readonly bool _detectWorkFileChange;
        private readonly string _workFilename;
        private bool _isDisposed = false;

        public event WorkfileChangedHandler WorkfileChanged;

        public bool EnableChangeNotify
        {
            get { return _fileWatcher.EnableRaisingEvents; }
            set { _fileWatcher.EnableRaisingEvents = value; }
        }

        public FileChangeNotifyProvider([Dependency("WorkFilename")] string workFilename, [Dependency("DetectWorkFileChange")] bool detectWorkFileChange)
        {
            _detectWorkFileChange = detectWorkFileChange;
            _workFilename = workFilename;

            if (_detectWorkFileChange)
            {
                if (File.Exists(_workFilename))
                {
                    string directory = Path.GetDirectoryName(_workFilename);
                    string filename = Path.GetFileName(_workFilename);
                    if (!string.IsNullOrWhiteSpace(directory) && !string.IsNullOrWhiteSpace(filename))
                    {
                        _fileWatcher = new FileSystemWatcher(directory, filename);
                        _fileWatcher.EnableRaisingEvents = true;
                    }
                }
                else
                    _fileWatcher = new FileSystemWatcher();

                _fileWatcher.Changed += OnChanged;
            }
        }
        
        private void OnChanged(object source, FileSystemEventArgs e)
        {
            WorkfileChanged();
        }

        public void Dispose()
        {
            if (!_isDisposed)
            {
                _fileWatcher.Dispose();
                _isDisposed = true;
            }
        }
    }
}
